import React, { useState, useEffect } from 'react';
import { Modal, Form, Table, Row, Col, Radio } from 'antd';
import notificationService from '../../../../../services/notificationService';
import type { FormInstance } from 'antd';
import { getFormInitialValues, resetFormToDefault, saveFormDefaultValues, saveFormInitialValues } from '../../../../../components/utils/formStorage';
import useIpcCalculation from '../../../hooks/useIpcCalculation';
import NumberField from '../../../../../components/common/NumberField';
import CalcControls from '../../../../../components/common/CalcControls';
import { ResultItem } from '../../../../../../shared/types';

// 定义荷载类型枚举
enum LoadType {
  PIPE = 'pipe',
  EXTERNAL = 'external'
}

// 定义完整的表单数据类型
interface FormValues {
  // 荷载类型
  loadType: LoadType;
  
  // 管道参数
  pipeOuterDiameter: number;
  pipeThickness: number;
  pipeDensity: number;
  mediumDensity: number;
  insulationOuterDiameter: number;
  insulationInnerDiameter: number;
  insulationDensity: number;
  equipmentWeight: number;
  spanLength: number;
  
  // 环境荷载参数
  windPressure: number;
  snowLoad: number;
  maintenanceLoad: number;
  temperatureDifference: number;
  pipeLinearExpansion: number;
  // 新增雪荷载计算所需参数
  projectionAreaOfSectionsPipesWalkways: number;
  totalContourAreaOfCalculationDeck: number;
}

interface InvertedTriangularExternalLoadCalculationProps {
  visible: boolean;
  onCancel: () => void;
  initialValues?: FormValues;
}

const InvertedTriangularExternalLoadCalculation: React.FC<InvertedTriangularExternalLoadCalculationProps> = ({ 
  visible, 
  onCancel,
  initialValues = {
    // 荷载类型
    loadType: LoadType.PIPE,
    // 管道参数
    pipeOuterDiameter: 0.325,
    pipeThickness: 0.01,
    pipeDensity: 7850,
    mediumDensity: 900,
    insulationOuterDiameter: 0.4,
    insulationInnerDiameter: 0.325,
    insulationDensity: 80,
    // 附属设备参数
    equipmentWeight: 500,
    spanLength: 14.0,
    // 环境荷载参数
    windPressure: 0.35,
    snowLoad: 0.2,
    maintenanceLoad: 0.5,
    temperatureDifference: 50,
    pipeLinearExpansion: 1.2e-5,
    // 雪荷载计算参数
    projectionAreaOfSectionsPipesWalkways: 4,
    totalContourAreaOfCalculationDeck: 12.2,
  }
}) => {
  const [form]: [FormInstance<FormValues>] = Form.useForm<FormValues>();
  const [resultData, setResultData] = useState<ResultItem[]>([]);
  const [prevVisible, setPrevVisible] = useState(visible);


  // 保存初始值到工具函数中
  useEffect(() => {
    // 为不同荷载类型保存不同的初始值
    saveFormDefaultValues(getFormKeyByLoadType(LoadType.PIPE), initialValues);
    saveFormDefaultValues(getFormKeyByLoadType(LoadType.EXTERNAL), {
      // 荷载类型
      loadType: LoadType.EXTERNAL,
      // 管道参数
      pipeOuterDiameter: 0.325,
      spanLength: 14.0,
      // 外部荷载参数
      windPressure: 0.35,
      snowLoad: 0.2,
      maintenanceLoad: 0.5,
      temperatureDifference: 50,
      pipeLinearExpansion: 1.2e-5,
      // 雪荷载计算参数
      projectionAreaOfSectionsPipesWalkways: 4,
      totalContourAreaOfCalculationDeck: 12.2,
    });
  }, [initialValues]);

  useEffect(() => {
    if (visible && !prevVisible) {
      try {
        // 根据当前荷载类型获取对应的参数
        const currentLoadType = form.getFieldValue('loadType') || LoadType.PIPE;
        const lastParams = getFormInitialValues(getFormKeyByLoadType(currentLoadType));
        
        // 使用 setTimeout 确保表单已经挂载后再设置字段值
        setTimeout(() => {
          if (lastParams && Object.keys(lastParams).length > 0) {
            form.setFieldsValue(lastParams);
          } else {
            // 使用默认值进行初始化
            const defaultParams = currentLoadType === LoadType.PIPE ? initialValues : {
              loadType: LoadType.EXTERNAL,
              pipeOuterDiameter: 0.325,
              spanLength: 14.0,
              windPressure: 0.35,
              snowLoad: 0.2,
              maintenanceLoad: 0.5,
              temperatureDifference: 50,
              pipeLinearExpansion: 1.2e-5,
            };
            form.setFieldsValue(defaultParams);
          }
          setResultData([]);
        }, 0);
      } catch (error) {
        console.error('表单初始化延迟，这是正常的:', error);
        // 使用 setTimeout 确保表单已经挂载后再设置字段值
        setTimeout(() => {
          form.setFieldsValue(initialValues);
          setResultData([]);
        }, 0);
      }
    }
    setPrevVisible(visible);
  }, [visible, prevVisible, initialValues, form]);

  // 使用自定义 Hook 进行 IPC 计算
  const { runCalculation } = useIpcCalculation();
  
  // 根据荷载类型获取对应的表单键
  const getFormKeyByLoadType = (loadType: LoadType) => {
    return loadType === LoadType.PIPE ? 'inverted-triangular-pipe-load' : 'inverted-triangular-external-load';
  };

  // 处理荷载计算
  const handleCalculate = async () => {
    try {
      // 验证表单
      const values = await form.validateFields();
      
      // 获取当前选择的荷载类型
      const loadType = form.getFieldValue('loadType');
      const currentFormKey = getFormKeyByLoadType(loadType);
      
      // 保存表单值
      saveFormInitialValues(currentFormKey, values);
      
      let apiRes;
      
      if (loadType === LoadType.PIPE) {
        // 管道荷载计算
        const pipeParams = {
          pipeOuterDiameter: values.pipeOuterDiameter,
          pipeThickness: values.pipeThickness,
          pipeDensity: values.pipeDensity,
          mediumDensity: values.mediumDensity,
          insulationOuterDiameter: values.insulationOuterDiameter || values.pipeOuterDiameter + 0.05, // 使用默认值或管道外径+保温层厚度
          insulationInnerDiameter: values.insulationInnerDiameter || values.pipeOuterDiameter, // 默认等于管道外径
          insulationDensity: values.insulationDensity,
          equipmentWeight: values.equipmentWeight,
          spanLength: values.spanLength,
        };
        
        apiRes = await runCalculation('crossing-calculate-pipe-load', pipeParams, (data: any) => {
          const pipeWeightLoad = data.pipeWeightLoad || 0;
          const mediumWeightLoad = data.mediumWeightLoad || 0;
          const insulationWeightLoad = data.insulationWeightLoad || 0;
          const equipmentWeightLoad = data.equipmentWeightLoad || 0;
          const totalPipeWeight = pipeWeightLoad + mediumWeightLoad + insulationWeightLoad + equipmentWeightLoad;
          
          return [
            { key: 'pipeWeightLoad', name: '管道自重荷载', value: pipeWeightLoad, unit: 'N/m', category: '管道荷载' },
            { key: 'mediumWeightLoad', name: '介质重量荷载', value: mediumWeightLoad, unit: 'N/m', category: '管道荷载' },
            { key: 'insulationWeightLoad', name: '保温层重量荷载', value: insulationWeightLoad, unit: 'N/m', category: '管道荷载' },
            { key: 'equipmentWeightLoad', name: '附属设备重量荷载', value: equipmentWeightLoad, unit: 'N/m', category: '管道荷载' },
            { key: 'totalPipeWeight', name: '管道总重', value: totalPipeWeight, unit: 'N/m', category: '管道荷载' },
          ];
        });
      } else {
        // 外部荷载计算
        const externalParams = {
          // 需要管道外径来计算风荷载等
          pipeOuterDiameter: values.pipeOuterDiameter,
          windPressure: values.windPressure,
          // 使用默认值填充缺失的环境参数
          windShapeFactor: 1.0,
          windHeightFactor: 1.0,
          windVibrationFactor: 1.0,
          snowDistributionCoefficient: 1.0,
          snowPressure: values.snowLoad,  // 正确映射雪荷载参数
          openingReductionCoefficient: 0.9,
          projectionAreaOfSectionsPipesWalkways: values.projectionAreaOfSectionsPipesWalkways,
          totalContourAreaOfCalculationDeck: values.totalContourAreaOfCalculationDeck,
          maintenanceLoad: values.maintenanceLoad,
          
          // 温度参数
          pipeThickness: 0.01, // 使用默认值
          elasticModulus: 200000, // 使用默认值
          thermalExpansion: values.pipeLinearExpansion,
          temperatureDifference: values.temperatureDifference,
        };
        
        apiRes = await runCalculation('crossing-calculate-external-load', externalParams, (data: any) => {
          return [
            { key: 'windLoad', name: '风荷载', value: data.windLoad || 0, unit: 'N/m', category: '外部荷载' },
            { key: 'snowLoad', name: '雪荷载', value: data.snowLoad || 0, unit: 'N/m', category: '外部荷载' },
            { key: 'maintenanceLoad', name: '维护荷载', value: data.maintenanceLoad || 0, unit: 'N/m', category: '外部荷载' },
            { key: 'temperatureLoad', name: '温度荷载', value: data.temperatureLoad || 0, unit: 'N', category: '外部荷载' },
          ];
        });
      }
      
      if (!apiRes.success) throw new Error('calculate-failed');
      
      // 直接使用处理后的结果数据
      if (Array.isArray(apiRes.results) && apiRes.results.length > 0) {
        setResultData(apiRes.results);
      } else {
        setResultData([]);
        notificationService.warning('计算成功但未返回结果数据');
      }
      
      return apiRes;
    } catch (error: any) {
      console.error('荷载计算过程中发生错误:', error);
      // 处理表单验证错误和其他错误
      if (!error || !error.errorFields) {
        notificationService.error('计算过程中发生错误');
      }
    }
  };
  
  // 使用Form.useWatch监听loadType变化
  const currentLoadType = Form.useWatch('loadType', form);

  // 监听荷载类型变化，清空结果
  useEffect(() => {
    if (currentLoadType !== undefined) {
      setResultData([]);
    }
  }, [currentLoadType]);

  const handleReset = () => {
    // 获取当前选择的荷载类型并重置对应表单
    const loadType = form.getFieldValue('loadType') || LoadType.PIPE;
    const currentFormKey = getFormKeyByLoadType(loadType);
    
    // 重置表单到默认保存的默认值并清空结果
    resetFormToDefault(form, currentFormKey);
      setResultData([]);
      notificationService.success('已重置到默认参数');
  };

  const columns: { title: string; dataIndex: string; key: string }[] = [
    { title: '项目', dataIndex: 'name', key: 'name' },
    { title: '数值', dataIndex: 'value', key: 'value' },
    { title: '单位', dataIndex: 'unit', key: 'unit' },
  ];

  return (
      <Modal
      title="外部荷载计算"
      open={visible}
      onCancel={onCancel}
      footer={null}
      width={1000}
    >
      <div style={{ display: 'flex', gap: 20 }}>
        <div style={{ flex: 1 }}>
          <div>
            <Form form={form} layout="vertical">
              {/* 荷载类型选择 */}
              <Form.Item label="荷载类型" name="loadType" rules={[{ required: true }]}>
                <Radio.Group>
                  <Radio.Button value={LoadType.PIPE}>管道荷载</Radio.Button>
                  <Radio.Button value={LoadType.EXTERNAL}>外部荷载</Radio.Button>
                </Radio.Group>
              </Form.Item>
              
              <Row gutter={16}>
                <Col span={12}>
                  {/* 公共参数 */}
                  <NumberField name="pipeOuterDiameter" label="管道外径 (m)" required min={0} step={0.001} />
                  <NumberField name="spanLength" label="跨度长度 (m)" required min={0} step={0.1} />
                  
                  {/* 管道荷载特有参数 */}
                  {form.getFieldValue('loadType') === LoadType.PIPE && (
                    <>
                      <NumberField name="pipeThickness" label="管道壁厚 (m)" required min={0} step={0.001} />
                      <NumberField name="pipeDensity" label="管道密度 (kg/m³)" required min={0} step={1} />
                      <NumberField name="mediumDensity" label="介质密度 (kg/m³)" required min={0} step={1} />
                      <NumberField name="insulationDensity" label="保温层密度 (kg/m³)" required min={0} step={1} />
                      <NumberField name="equipmentWeight" label="附属设备总重量 (kg)" required min={0} step={1} />
                    </>
                  )}
                  
                  {/* 外部荷载特有参数 */}
                  {form.getFieldValue('loadType') === LoadType.EXTERNAL && (
                    <>
                      <NumberField name="windPressure" label="风压 (kPa)" required min={0} step={0.01} />
                      <NumberField name="snowLoad" label="雪荷载 (kPa)" required min={0} step={0.01} />
                      <NumberField name="maintenanceLoad" label="维护荷载 (kPa)" required min={0} step={0.01} />
                      <NumberField name="temperatureDifference" label="温度差 (°C)" required min={0} step={1} />
                      <NumberField name="pipeLinearExpansion" label="管道线膨胀系数" required min={0} step={1e-7} />
                      {/* 雪荷载计算所需参数 */}
                      <NumberField name="projectionAreaOfSectionsPipesWalkways" label="管道及走道板投影面积 (m²)" required min={0} step={0.1} />
                      <NumberField name="totalContourAreaOfCalculationDeck" label="桥面轮廓总面积 (m²)" required min={0} step={0.1} />
                    </>
                  )}
                </Col>
                
                <Col span={12}>
                  {/* 保温层参数（仅在管道荷载类型下显示） */}
                  {form.getFieldValue('loadType') === LoadType.PIPE && (
                    <>
                      <NumberField name="insulationOuterDiameter" label="保温层外径 (m)" required min={0} step={0.001} />
                      <NumberField name="insulationInnerDiameter" label="保温层内径 (m)" required min={0} step={0.001} />
                    </>
                  )}
                </Col>
              </Row>
              
              <Form.Item style={{ marginTop: 24 }}>
                <CalcControls
                  onCalculate={handleCalculate}
                  onReset={handleReset}
                />
              </Form.Item>
            </Form>
          </div>
        </div>
        
        <div style={{ flex: 1 }}>
          <Table 
            dataSource={resultData} 
            columns={columns} 
            pagination={false} 
            bordered 
            rowKey="key"
            scroll={{ y: 350 }}
            style={{ marginTop: 24 }}
          />
        </div>
      </div>
    </Modal>
    );
};

export default InvertedTriangularExternalLoadCalculation;